package com.ls.pattern.flyweight.sql;

import java.sql.Connection;
import java.sql.DriverManager;
import java.util.Vector;

/**
 * jdbc 连接工厂
 *
 * @author 挥之以墨
 */
public class CollectionPool {

    private Vector<Connection> pool = new Vector<>();

    private String driverClassName = "com.mysql.cj.jdbc.Driver";
    private String url = "jdbc:mysql://localhost:3306/pattern?serverTimezone=CTT&useUnicode=true&characterEncoding=utf-8&allowMultiQueries=true";
    private String userName = "root";
    private String password = "admin";

    private CollectionPool() {
        try {
            Class.forName(driverClassName);
            for (int i = 0; i < 2; i++) {
                Connection conn = DriverManager.getConnection(url, userName, password);
                pool.add(conn);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static CollectionPool getInstance() {
        return InnerClass.POOL;
    }

    public Connection getConnection() {
        if (pool.size() > 0) {
            Connection conn = pool.get(0);
            pool.remove(conn);
            return conn;
        }
        return null;
    }

    public synchronized void release(Connection conn) {
        pool.add(conn);
    }

    private static class InnerClass {
        private static CollectionPool POOL = new CollectionPool();
    }
}
